package com.fishingwithme.infrastructure;

import com.fishingwithme.infrastructure.dtos.DTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public DTO<Boolean> handleValidationException(MethodArgumentNotValidException ex) {
        log.error(ex.getMessage());
        return DTO.fail(Boolean.FALSE, 400, "请求失败.");
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public DTO<Boolean> handleMessageNotReadableException(HttpMessageNotReadableException ex) {
        log.error(ex.getMessage());
        return DTO.fail(Boolean.FALSE, 400, "请求失败.");
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public DTO<Boolean> handleGeneralException(Exception ex) {
        log.error(ex.getMessage());
        return DTO.fail(Boolean.FALSE, 400, "请求失败.");
    }
}
